﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using mal.balades.Business.DataModel;

namespace mal.balades.Business.Web
{
    public static class HtmlFormatVisitLink
    {
        public static string Format(string text)
        {
            HtmlDocument doc = new HtmlDocument();
            string result = text;
            doc.LoadHtml(text);
            if (doc.DocumentNode.SelectNodes("//url") != null)
            {
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//url"))
                {
                    string outerHtml = link.OuterHtml;
                    string innerHtml = link.InnerHtml;
                    string type = link.Attributes["type"].Value;
                    string value = link.Attributes["value"].Value;

                    if (type == "visit")
                    {
                        Visit visitLink = BaladesManagerProxy.Instance.GetVisit(value);
                        if (visitLink != null)
                        {
                            string htmllink = string.Format("<a href=\"{0}\" title=\"{1}\">{2}</a>"
                                , UrlManager.VisitUrl(visitLink), visitLink.Title, innerHtml);

                            result = result.Replace(outerHtml, htmllink.ToString());
                        }
                    }
                    else if (type == "category")
                    {
                        Category categoryLink = BaladesManagerProxy.Instance.GetCateogries().Where(c => c.UrlName == value).SingleOrDefault();
                        if (categoryLink != null)
                        {
                            string htmllink = string.Format("<a href=\"{0}\" title=\"{1}\">{2}</a>"
                                , UrlManager.CategoryUrl(categoryLink.UrlName), categoryLink.Name, innerHtml);

                            result = result.Replace(outerHtml, htmllink.ToString());
                        }
                    }

                    else if (type == "zone")
                    {
                        result = result.Replace(outerHtml, string.Format("<b>{0}</b>", innerHtml));
                    }
                }
            }

            return result;
        }
    }
}
